package com.example.demotest.service;

import com.example.demotest.exception.NicknameAlreadyExistsException;
import com.example.demotest.exception.UsernameAlreadyExistsException;
import com.example.demotest.pojo.ResponseMessage;
import com.example.demotest.pojo.User;
import com.example.demotest.pojo.UserProfile;
import com.example.demotest.pojo.dto.ChangePasswordDto;
import com.example.demotest.pojo.dto.UserDto;
import com.example.demotest.pojo.dto.UserProfileDto;
import com.example.demotest.repository.UserProfileRepository;
import com.example.demotest.repository.UserRepository;
import com.example.demotest.util.JWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.transaction.Transactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


import java.util.Optional;

@Service
public class UserService implements IUserService{

    @Autowired
    UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JWT jwtUtil;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Override
    public User add(UserDto user) {

        User userPojo = new User();

        BeanUtils.copyProperties(user, userPojo);

        return userRepository.save(userPojo);
        //调用数据

    }

    @Override
    public User  edit(UserDto user) {
        User userPojo = new User();

        BeanUtils.copyProperties(user, userPojo);
        return userRepository.save(userPojo);
    }

    @Override
    public void delete(Integer userId) {
         userRepository.deleteById(userId);
    }

    @Override
    @Transactional
    public User register(UserDto userDto) {
        if (userRepository.findByUserName(userDto.getUserName()).isPresent()) {
            throw new UsernameAlreadyExistsException("用户名已存在");
        }

        // 检查昵称是否存在
        if (userRepository.findByNickname(userDto.getNickname()).isPresent()) {
            throw new NicknameAlreadyExistsException("昵称已被使用");
        }

        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setPassword(passwordEncoder.encode(userDto.getPassword()));

        User savedUser = userRepository.save(user);

        UserProfile profile = new UserProfile();
        profile.setUser(savedUser); // 不再设置 userId，MapsId 会自动处理
        profile.setEmail("null");
        profile.setAvatarUrl("https://example.com/default-avatar.png");
        profile.setGender("未知");
        profile.setPhone("");
        profile.setAddress("");

        userProfileRepository.save(profile);

        return savedUser;
    }

    public Optional<User> findByUserName(String userName) {
        return userRepository.findByUserName(userName);
    }

    @Override
    public ResponseMessage<User> login(UserDto userDto) {
        Optional<User> userOptional = findByUserName(userDto.getUserName());

        if (userOptional.isPresent()) {
            User user = userOptional.get();
            if (passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
                System.out.println("登录成功");
                String token = JWT.generateToken(String.valueOf(user.getUserId()));
                return ResponseMessage.successWithToken(user, token); // 自定义结构

            }
        }

        return ResponseMessage.error(401, "用户名或密码错误");
    }

    @Override
    public UserDto getUser(Integer userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new IllegalArgumentException("用户不存在或者参数异常"));

        UserDto dto = new UserDto();
        dto.setUserID(user.getUserId());
        dto.setUserName(user.getUserName());
        dto.setNickname(user.getNickname());
        dto.setAvatarUrl(user.getAvatarUrl()); // 假设你把头像存在 images 字段里
        // 根据需要继续加字段

        return dto;
    }

    //查看信息
    @Override
    public UserProfile getUserInformation(Integer userId) {
        return userProfileRepository.findById(userId).orElse(null);
    }

    @Override
    @Transactional
    public UserProfile updateUserProfile(Integer userId, UserProfileDto dto) {
        UserProfile profile = userProfileRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户资料不存在"));

        profile.setEmail(dto.getEmail());
        profile.setAvatarUrl(dto.getAvatarUrl());
        profile.setGender(dto.getGender());
        profile.setPhone(dto.getPhone());
        profile.setAddress(dto.getAddress());

        return userProfileRepository.save(profile);
    }

    @Override
    @Transactional
    public User updateUserPassword(Integer userId, ChangePasswordDto dto) {

        // 1. 查找用户
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 2. 校验旧密码
        if (!passwordEncoder.matches(dto.getOldPassword(), user.getPassword())) {
            throw new RuntimeException("旧密码不正确");
        }

        // 3. 设置新密码（加密）
        String encodedNewPassword = passwordEncoder.encode(dto.getNewPassword());
        user.setPassword(encodedNewPassword);

        // 4. 保存用户
        return userRepository.save(user);
    }

    @Override
    public User updateUserNickname(Integer userId, User dto) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        user.setNickname(dto.getNickname());
        return userRepository.save(user);
    }

    @Override
    public void updateAvatar(Integer userId, String avatarUrl) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        user.setAvatarUrl(avatarUrl); // 或 setAvatarUrl，根据你的字段命名
        userRepository.save(user);
    }

}
